package com.example.config;

import org.apache.tomcat.util.security.MD5Encoder;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //首页所有人可以访问，功能页只有对应有权限的人才能访问
        //请求授权的规则
        http.authorizeRequests()
                .antMatchers("/").permitAll()
                .antMatchers("/level1/**").hasRole("vip1")
                .antMatchers("/level2/**").hasRole("vip2")
                .antMatchers("/level3/**").hasRole("vip3");

        //设置没有权限默认跳转至登录页面
        http.formLogin().loginPage("/toLogin").usernameParameter("username").usernameParameter("password").loginProcessingUrl("/login");

        //注销登录
        //http.logout();
        http.logout().logoutSuccessUrl("/");

        //开启记住我功能，cookie（默认保存14天）
        http.rememberMe().rememberMeParameter("remeber");
    }

    //认证规则
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
                .withUser("admin")
                .password(new BCryptPasswordEncoder().encode("admin"))
                .roles("vip1")
                .and()
                .withUser("root")
                .password(new BCryptPasswordEncoder().encode("root"))
                .roles("vip1", "vip2", "vip3");
    }
}
